package com.hgw.imsever.netty;

import com.hgw.imsever.common.utils.RedisUtil;
import com.hgw.imsever.netty.handler.BinaryWebSocketFrameHandler;
import com.hgw.imsever.netty.handler.HeartBeatHandler;
import com.hgw.imsever.service.UserGroupService;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class ChannelInitiallizer extends ChannelInitializer<SocketChannel> {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserGroupService userGroupService;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        socketChannel.pipeline()
                .addLast("idle", new IdleStateHandler(30, 30, 60))
                .addLast("hearBeat", new HeartBeatHandler(redisUtil))
                .addLast("codec", new HttpServerCodec())
                .addLast("chunked", new ChunkedWriteHandler())
                .addLast("aggreator", new HttpObjectAggregator(65536))
                .addLast(new WebSocketServerProtocolHandler("/ws/chat"))
                .addLast(new BinaryWebSocketFrameHandler(redisUtil, userGroupService));
    }
}
